package com.hz.cheetah.client;

import com.hz.cheetah.common.bean.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by yangchuan on 16/7/6.
 */
public class ClientManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientManager.class);
    public static ConcurrentHashMap<String, CheetahClient> channelMap = new ConcurrentHashMap<>();//PlatformDependent.newConcurrentHashMap();


    /**
     * 用于服务器之间有其它网络设备的服务器环境，如果服务器之间是直连的就不需要heartbeat
     */
    private static class watchdog implements Runnable {

        public void run() {
            while (true) {
                try {
                    for (CheetahClient client : channelMap.values()) {
                        if (client == null || !client.isConnected()) {
                            continue;
                        }
                        if (System.currentTimeMillis() - client.lastmsgtime > 180 * 1000) {
                            if(client.tryitnum < 3) {
                                client.tryitByheartbeat();
                                LOGGER.warn(" try sent heatbeat msg:{}", client.tryitnum);
                            }else{
                                client.close();
                            }
                        }else{
                            client.tryitnum = 0;
                        }
                    }
                    Thread.sleep(3000);
                } catch (Throwable e) {
                    LOGGER.error("Exception when scan the timeout invocation of remoting.", e);
                }
            }
        }
    }

    static {
        Thread th = new Thread(new watchdog(), "ResponseTimeoutScanTimer");
        th.setDaemon(true);
        th.start();
    }
}
